/*
 * File:   main.cpp
 * Author: Kreyl
 *
 * Created on May 27, 2011, 6:37 PM
 */

#include "stm32f4xx.h"
#include "kl_lib_f4xx.h"
#include "clocking.h"

#include "main.h"
#include "flashloader_support.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_usart.h"

#include <stdlib.h>


// Prototypes
void GeneralInit(void);

// ============================ Implementation ================================
int main(void) {
// Oscillator on board STM32F4Discovry user manual p.18
    uint8_t ClkResult = 1;

    Clk.SetupFlashLatency(8, 3000);  // Setup Flash Latency for clock in MHz
    Clk.PLLDisable();
//     8 MHz/4 = 2; 2*96 = 192; 192/4 = 48 (preAHB divider); 192/4 = 48 (USB clock)
    Clk.SetupPLLDividers(4, 96, pllSysDiv4, 4);
//    // 8MhH/1 = 8 MHz core clock. APB1 & APB2 clock derive on AHB clock
    Clk.SetupBusDividers(ahbDiv1, apbDiv1, apbDiv1);
    if((ClkResult = Clk.SwitchToPLL()) == 0) Clk.HSIDisable();
    Clk.UpdateFreqValues();

    GeneralInit();

    PinSetupOut(GPIOD, 12, omPushPull, pudPullUp, ps100MHz); // 12 - Green
    PinSetupOut(GPIOD, 13, omPushPull, pudPullUp, ps100MHz); // 13 - Orange
    PinSetupOut(GPIOD, 14, omPushPull, pudPullUp, ps100MHz); // 14 - Red
    PinSetupOut(GPIOD, 15, omPushPull, pudPullUp, ps100MHz); // 15 - Blue

    PinSetupIn(GPIOA, 0, pudPullDown);
    // ==== Main cycle ====
    uint32_t Tmr;
    bool KWP = false;

    while(1) {
        if(Delay.Elapsed(&Tmr, 99)){
            if (PinIsSet(GPIOA, 0) && !KWP) {
                PinToggle(GPIOD, 13);

                KWP = true;
            }
            else if (!PinIsSet(GPIOA, 0) && KWP) KWP = false;
        }
    } // while(1)
}

void GeneralInit(){
    Delay.Init();
    Uart.Init(115200);

    Uart.Printf("\rCortex-M4 RJ v.%u\r", CURRENT_FIRMWARE_VERSION);
}
